/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package me.zhengjie.service.impl;

import lombok.val;
import me.zhengjie.config.FileProperties;
import me.zhengjie.domain.Answers;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.utils.*;
import lombok.RequiredArgsConstructor;
import me.zhengjie.repository.AnswersRepository;
import me.zhengjie.service.AnswersService;
import me.zhengjie.service.dto.AnswersDto;
import me.zhengjie.service.dto.AnswersQueryCriteria;
import me.zhengjie.service.mapstruct.AnswersMapper;
import org.apache.logging.log4j.util.StringBuilders;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import java.io.File;
import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotBlank;

import org.springframework.web.multipart.MultipartFile;

/**
 * @author wuhj
 * @website https://eladmin.vip
 * @description 服务实现
 * @date 2023-09-16
 **/
@Service
@RequiredArgsConstructor
public class AnswersServiceImpl implements AnswersService {

    private final AnswersRepository answersRepository;
    private final AnswersMapper answersMapper;

    private final FileProperties properties;

    @Override
    public PageResult<AnswersDto> queryAll(AnswersQueryCriteria criteria, Pageable pageable) {
        Page<Answers> page = answersRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        return PageUtil.toPage(page.map(answersMapper::toDto));
    }

    @Override
    public List<AnswersDto> queryAll(AnswersQueryCriteria criteria) {
        return answersMapper.toDto(answersRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }

    @Override
    @Transactional
    public AnswersDto findById(Long id) {
        Answers answers = answersRepository.findById(id).orElseGet(Answers::new);
        ValidationUtil.isNull(answers.getId(), "Answers", "id", id);
        return answersMapper.toDto(answers);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create(Answers resources) {
        answersRepository.save(resources);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Answers resources) {
        Answers answers = answersRepository.findById(resources.getId()).orElseGet(Answers::new);
        ValidationUtil.isNull(answers.getId(), "Answers", "id", resources.getId());
        answers.copy(resources);
        answersRepository.save(answers);
    }

    @Override
    public void deleteAll(Long[] ids) {
        for (Long id : ids) {
            answersRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<AnswersDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (AnswersDto answers : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("试卷人", answers.getUserId());
            map.put("科目", answers.getSubjectId());
            map.put("提交答案", answers.getContent());
            map.put("系统判分", answers.getScore());
            map.put("最终判分", answers.getFinalScore());
            map.put("开始时间", answers.getStartTs());
            map.put("备注", answers.getDesc());
            map.put("提交时间", answers.getCommitTs());
            map.put("提交人", answers.getCommitor());
            map.put("更新人", answers.getUpdator());
            map.put("更新时间", answers.getUpdateTs());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public Map<String, String> uploadSnapshots(Long answerId, String cardId, MultipartFile[] files) {
        Answers answers = answersRepository.findById(answerId).get();
        String[] oldpaths = answers.getContent().split(",");
        for (String old : oldpaths) {
            FileUtil.del(old);
        }
        StringJoiner sj = new StringJoiner(",");
        for (MultipartFile file : files) {
            // 验证文件上传的格式
            String image = "gif jpg png jpeg";
            String fileType = FileUtil.getExtensionName(file.getOriginalFilename());
            if (fileType != null && !image.contains(fileType)) {
                throw new BadRequestException("文件格式错误！, 仅支持 " + image + " 格式");
            }
            File snapshot = FileUtil.upload(file, properties.getPath().getPath() + File.separator + "answers");
            sj.add(Objects.requireNonNull(snapshot).getPath());
        }
        answers.setContent(sj.toString());
        answersRepository.save(answers);
        return new HashMap<String, String>(1) {{
            put("snapshots", sj.toString());
        }};
    }
}